package com.my.netty.basic.channel;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class EventLoopServer {
    /*
        EventLoop处理IO事件
     */
    public static void main(String[] args) {
        new ServerBootstrap()
            .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel sc) throws Exception {
                log.info("获取客户端连接：{}", sc.remoteAddress());
                sc.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    log.info("接收客户端{}发送数据: {}", ctx.channel().remoteAddress(), buf.toString(Charset.defaultCharset()));
                }
                });
                }
            })
            .bind(8080);
        log.info("服务器已启动...");
    }
}
